<?php
/**
 * CommonHelper class file.
 *
 * @author Zhang Jinlong <466028373@qq.com>
 * @link http://www.ijianzhi.cn
 * @copyright Copyright &copy; 2013 DianJin Soft
 */

class Helper
{
    /**
     * 生成随机数
     * @param integer $count
     * @param string $addchars
     * @param boolean $arrayOut
     * @param boolean $unique
     * @return mixed
     */
    public static function random($count = 6, $addchars = '', $arrayOut = FALSE, $unique = FALSE)
    {
        $chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.$addchars;
        $tmp = range(0, strlen($chars) - 1);

        if ($unique === TRUE)
        {
            shuffle($tmp);
            $keys = array_slice($tmp, 0, $count);
        }
        else
        {
            $keys = array_rand($tmp, $count);
        }

        $random = array();

        foreach ($keys as $value)
        {
            $random[] = $chars{$value};
        }

        if ($arrayOut === TRUE)
        {
            return $random;
        }
        else
        {
            return implode('', $random);
        }
    }

    /**
     * 加密字符串
     * @param string $string
     */
    public static function encrypt($string)
    {
        $keys = array('CI9SsW', 'bxlYmF');
        $agent = substr($_SERVER['HTTP_USER_AGENT'] ? $_SERVER['HTTP_USER_AGENT'] : 'ROBOTS', -5, 5);
        $vala = 0;

        for ($i = 0; $i < strlen($agent); $i++)
        {
            $vala += ord($agent{$i});
        }

        $vala = substr(strval($vala), -1, 1);
        $valb = self::random(4, '/');
        $flag = (strlen($string) % 2) == 1 ? 1 : 0;
        $tmp = $valb.$keys[$flag].base64_encode($string).$keys[$flag^1];
        $tmp2 = '';

        for ($i = 0; $i < strlen($tmp) * 2; $i++)
        {
            if ($i % 2 == 0)
            {
                $tmp2 .= $valb{$i / 2 % 4};
            }
            else
            {
                $tmp2 .= $tmp{($i - 1) / 2};
            }
        }

        $tmp = $valb.base64_encode(strrev($tmp2)).$flag.$vala;

        return $tmp;

    }

    /**
     * 解密字符串
     * @param string $string
     */
    public static function decrypt($string)
    {
        $keys = array('CI9SsW', 'bxlYmF');
        $agent = substr($_SERVER['HTTP_USER_AGENT'] ? $_SERVER['HTTP_USER_AGENT'] : 'ROBOTS', -5, 5);
        $vala = 0;

        for ($i = 0; $i < strlen($agent); $i++)
        {
            $vala += ord($agent{$i});
        }

        $vala = substr(strval($vala), -1, 1);
        $valb = substr($string, 0, 4);

        if (substr($string, -1, 1) != $vala)
        {
            return FALSE;
        }

        $flag = intval(substr($string, -2, 1));
        $tmp = base64_decode(substr($string, 4, strlen($string) - 6));
        $tmp = strrev($tmp);
        $tmp2 = '';

        for ($i = 0; $i < strlen($tmp); $i++)
        {
            if ($i % 2 == 1)
            {
                $tmp2 .= $tmp{$i};
            }
        }

        if (
            substr($tmp2, 4, 6) != $keys[$flag]
            || substr($tmp2, -6, 6) != $keys[$flag^1]
            || substr($tmp2, 0, 4) != $valb)
        {
            return FALSE;
        }

        $tmp2 = base64_decode(substr($tmp2, 10, strlen($tmp2) - 16));

        return $tmp2;
    }

    /**
    * 获得分页
    * @param integer $totalRecords
    * @param integer $pageSize
    * @param integer $currentPage
    * @param string $url
    * @return string
    */
    public static function getPages($totalRecords, $pageSize, $currentPage, $url)
    {
        $pager = new Pager($totalRecords, $pageSize, $currentPage, $url);

        return $pager->getMultLink();
    }

    /**
     * 截取字符串
     * @param string $string
     * @param integer $length
     * @param string $dot
     */
    public static function cutStr($string, $length, $dot = ' ...')
    {
        if (strlen($string) <= $length)
        {
            return $string;
        }

        $pre = chr(1);
        $end = chr(1);
        $string = str_replace(array('&amp;', '&quot;', '&lt;', '&gt;'), array($pre.'&'.$end, $pre.'"'.$end, $pre.'<'.$end, $pre.'>'.$end), $string);

        $strcut = '';
        $n = $tn = $noc = 0;

        while ($n < strlen($string))
        {
            $t = ord($string[$n]);

            if ($t == 9 || $t == 10 || (32 <= $t && $t <= 126))
            {
                $tn = 1; $n++; $noc++;
            }
            else if (194 <= $t && $t <= 223)
            {
                $tn = 2; $n += 2; $noc += 2;
            }
            else if (224 <= $t && $t <= 239)
            {
                $tn = 3; $n += 3; $noc += 2;
            }
            else if (240 <= $t && $t <= 247)
            {
                $tn = 4; $n += 4; $noc += 2;
            }
            else if (248 <= $t && $t <= 251)
            {
                $tn = 5; $n += 5; $noc += 2;
            }
            else if( $t == 252 || $t == 253)
            {
                $tn = 6; $n += 6; $noc += 2;
            }
            else
            {
                $n++;
            }

            if ($noc >= $length)
            {
                break;
            }
        }

        if ($noc > $length)
        {
            $n -= $tn;
        }

        $strcut = substr($string, 0, $n);
        $strcut = str_replace(array($pre.'&'.$end, $pre.'"'.$end, $pre.'<'.$end, $pre.'>'.$end), array('&amp;', '&quot;', '&lt;', '&gt;'), $strcut);

        $pos = strrpos($strcut, chr(1));

        if ($pos !== false)
        {
            $strcut = substr($strcut,0,$pos);
        }

        return $strcut.$dot;
    }

    /**
     * 显示跳转信息
     * @param string $message
     * @param string $forwardUrl
     * @param integer $status 1 成功信息，2 失败信息
     * @param integer $waitTime
     * @param string $otherScropt
     */
    public static function showMessage($message, $forwardUrl, $waitTime = 3, $status = Constants::OPERATION_SUCCEED, $otherScript = '')
    {
        if ($waitTime <= 0)
        {
            Yii::app()->request->redirect($forwardUrl);
        }

        $controller = new CController('message');

        $controller->renderPartial('/site/message', array(
            'message' => $message,
            'forwardUrl' => $forwardUrl,
            'status' => $status,
            'waitTime' => $waitTime,
            'otherScript' => $otherScript,
        ));

        Yii::app()->end();
    }

    /**
     * 生成OAUTH需要的STATE数据
     * @return string
     */
    public static function generateOAuthState()
    {
        return md5(uniqid(rand(), TRUE));
    }

    /**
     * 生成日志数据
     * @param mixed $message
     */
    public static function generateLogMessage($message)
    {
    	$logMsg = array();

    	if ($message instanceof Exception)
    	{
    	    $logMsg[] = "Type: Exception";
    		$logMsg[] = 'ExceptionClass: '.get_class($message);

    		if ($message instanceof CHttpException)
    		{
    			$logMsg[] = 'StatusCode: '.$message->statusCode;
    		}

    		if ($message instanceof OAuthException)
    		{
                $logMsg[] = 'ErrorCode: '.$message->errorCode;
    		}

    		$logMsg[] = 'Message: '.$message->getMessage();
    		$logMsg[] = 'Code: '.$message->getCode();
    		$logMsg[] = 'File: '.$message->getFile();
    		$logMsg[] = 'Line: '.$message->getLine();
    	}
    	else
    	{
    		$logMsg[] = $message;
    	}

        return implode(' | ', $logMsg);
    }
}